package com.example.eventbus;

import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

import com.example.eventbus.bean.MessageEvent;
import com.example.eventbus.subscribe.MySubscribe;

import org.greenrobot.eventbus.EventBus;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private TextView textView;

    @SuppressLint("MissingInflatedId")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        findViewById(R.id.button).setOnClickListener(this);
        textView = findViewById(R.id.textView);
    }

    //发布事件
    @Override
    public void onClick(View view) {
        EventBus.getDefault().post(new MessageEvent("Hello World"));
    }

    @Override
    protected void onStart() {
        super.onStart();
        //注册订阅者
        //注册与注销需要保持在对称的生命周期中
        EventBus.getDefault().register(new MySubscribe(this));
    }

    @Override
    protected void onStop() {
        super.onStop();
        //注销订阅者
        EventBus.getDefault().unregister(new MySubscribe(this));
    }


}